import {useNavigate} from "react-router-dom";
import React, {useEffect, useState} from "react";
import {AppBar, Container, Divider, IconButton, List, ListItem, ListItemText, Toolbar, Typography} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import Box from "@mui/material/Box";


const CityList = function CityList() {
    const navigate = useNavigate();

    const [cityData, setCityData] = useState([
        {"id": "1", "name": "chengdu"},
        {"id": "2", "name": "chongqing"},
        {"id": "3", "name": "hefei"},
        {"id": "4", "name": "hanghzou"},
        {"id": "5", "name": "shenzhen"},
        {"id": "6", "name": "guangzhou"},
        {"id": "7", "name": "nanjing"},
        {"id": "8", "name": "zhenjiang"},
        {"id": "9", "name": "luzhou"},
        {"id": "11", "name": "anshun11"},
        {"id": "12", "name": "anshun12"},
        {"id": "13", "name": "anshun13"},
        {"id": "14", "name": "anshun14"},
        {"id": "15", "name": "anshun15"},
        {"id": "16", "name": "anshun16"},
        {"id": "17", "name": "anshun17"},
        {"id": "18", "name": "anshun18"},
        {"id": "19", "name": "anshun19"},
        {"id": "20", "name": "anshun20"},
        {"id": "21", "name": "anshun21"},
        {"id": "22", "name": "anshun22"},
        {"id": "23", "name": "anshun22"},
        {"id": "24", "name": "anshun22"},
        {"id": "25", "name": "anshun22"},
        {"id": "26", "name": "anshun22"},
        {"id": "27", "name": "yangguo"},
        {"id": "28", "name": "yangzi"},
        {"id": "29", "name": "xibei"},
        {"id": "30", "name": "xian"},
        {"id": "31", "name": "zhonghua"},
        // ... 其他城市数据
    ]);

    const [selectedCity, setSelectedCity] = useState(null);
    const [activeLetter, setActiveLetter] = useState(null);

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);


    useEffect(() => {
        // 模拟从后端 API 获取城市数据
        const fakeApiResponse = [
            {"id": "1", "name": "chengdu"},
            {"id": "2", "name": "chongqing"},
            {"id": "3", "name": "hefei"},
            {"id": "4", "name": "hanghzou"},
            {"id": "5", "name": "shenzhen"},
            {"id": "6", "name": "guangzhou"},
            {"id": "7", "name": "nanjing"},
            {"id": "8", "name": "zhenjiang"},
            {"id": "9", "name": "luzhou"},
            {"id": "11", "name": "anshun11"},
            {"id": "12", "name": "anshun12"},
            {"id": "13", "name": "anshun13"},
            {"id": "14", "name": "anshun14"},
            {"id": "15", "name": "anshun15"},
            {"id": "16", "name": "anshun16"},
            {"id": "17", "name": "anshun17"},
            {"id": "18", "name": "anshun18"},
            {"id": "19", "name": "anshun19"},
            {"id": "20", "name": "anshun20"},
            {"id": "21", "name": "anshun21"},
            {"id": "22", "name": "anshun22"},
            {"id": "23", "name": "anshun22"},
            {"id": "24", "name": "anshun22"},
            {"id": "25", "name": "anshun22"},
            {"id": "26", "name": "anshun22"},
            {"id": "27", "name": "yangguo"},
            {"id": "28", "name": "yangzi"},
            {"id": "29", "name": "xibei"},
            {"id": "30", "name": "xian"},
            {"id": "31", "name": "zhonghua"},
            // ... 其他城市数据
        ];

        // 对城市数据按照名称进行排序
        const sortedCityData = fakeApiResponse.sort((a, b) => a.name.localeCompare(b.name));

        // @ts-ignore
        setCityData(sortedCityData);
    }, []);

    const handleCityClick = (city: string) => {
        // 选择城市后跳转回搜索框页面，并携带选择的城市名字
        console.log(city)
        // 选择城市后跳转到 IndexPage 并传递城市参数
        navigate('/indexPage', {state: {selectedCity: city}});
    };

    const handleLetterClick = (letter: any) => {
        console.log(letter)
        //获取到第一个以G开头的城市的DIV，并跳转到那
        const desiredCity = cityData.find(city => city.name.charAt(0).toUpperCase() === letter);
        console.log(desiredCity)

        if (desiredCity) {
            const cityElement = document.getElementById(`city-` + desiredCity.id);
            console.log(cityElement)
            if (cityElement) {
                cityElement.scrollIntoView({behavior: 'smooth', block: 'start'});
                const letterElement = document.getElementById(`letter-${letter}`);
                // @ts-ignore
                setActiveLetter(letterElement);
            }
        }


    };

    const handleScroll = () => {

        const letters = Array.from({length: 26}, (_, index) => String.fromCharCode(65 + index));

        const container = document.getElementById('cityListContainer');

        if (container) {
            // 获取当前屏幕高度
            const windowHeight = window.innerHeight;
            // 获取所有 ID 以 city 开头的 DIV 元素，遍历他们，获得处于当前屏幕中心的城市名称，拿着名字去点亮右侧索引栏
            const cityElements = document.querySelectorAll('#cityListContainer ul div[id^="city"]');
            cityElements.forEach(cityElement => {
                const cityRect = cityElement.getBoundingClientRect();
                const cityName = cityElement.getAttribute('id');

                console.log(`City: ${cityName}, Top: ${cityRect.top}, Bottom: ${cityRect.bottom}`);
                if (cityRect.top < windowHeight / 2 && cityRect.bottom > windowHeight / 2) {
                    console.log('cityName', cityName)
                    console.log('cityData', cityData)
                    const desiredCity = cityData.find(city => 'city-' + city.id === cityName);
                    if (desiredCity) {
                        const cityName = desiredCity.name;
                        const firstLetter = cityName[0].toUpperCase();
                        console.log("城市的第一个字母:", firstLetter);

                        // 找到当前可见区域中心位置对应的字母
                        const currentLetter = letters.find((letter) => {
                            const letterElement = document.getElementById(`letter-${letter}`);
                            if (letterElement) {
                                return `letter-${firstLetter}` === letterElement.getAttribute('id');
                            }
                            return false;
                        });
                        // @ts-ignore
                        setActiveLetter(currentLetter);
                    } else {
                        console.log("未找到指定的城市");
                    }
                }
            });
            console.log('---5-----');
        }
    };


    const handleGoBack = () => {
        // 返回到上一页
        navigate(-1);
    };

    return (
        <div>
            <AppBar position="fixed" style={{height: '47px'}}>
                <Toolbar>
                    <IconButton onClick={handleGoBack} color="inherit">
                        <ArrowBackIcon/>
                    </IconButton>
                    <Typography variant="h6" sx={{flexGrow: 1, textAlign: 'center'}}>
                        城市选择
                    </Typography>
                </Toolbar>
            </AppBar>

            <div style={{paddingTop: '60px', paddingBottom: '90px'}}>

                {/* 字母导航栏 */}
                <div style={{
                    position: 'fixed',
                    top: '48.5%',
                    // bottom: '10%',
                    right: 0,
                    transform: 'translateY(-50%)',
                    // paddingTop: '90px',
                    // paddingBottom: '90px'
                    maxHeight: '700px',
                    overflowY: 'auto'
                }}>
                    {Array.from({length: 26}, (_, index) => String.fromCharCode(65 + index)).map((letter) => (
                        <span
                            key={letter}
                            id={`letter-${letter}`}
                            style={{
                                display: 'block',
                                textAlign: 'center',
                                cursor: 'pointer',
                                fontWeight: activeLetter === letter ? 'bold' : 'normal'
                            }}
                            onClick={() => handleLetterClick(letter)}
                        >
                             {letter}
                        </span>
                    ))}
                </div>

                {/* 城市列表 */}
                <div id="cityListContainer" style={{padding: '0 20px'}}>
                    <List>
                        {cityData.map((city, index) => (
                            <div key={city.id} id={`city-${city.id}`}>
                                {index === 0 || city.name.charAt(0) !== cityData[index - 1].name.charAt(0) ? (
                                    <div>
                                        <Divider/>
                                        <Typography variant="subtitle1" style={{margin: '5px 0'}}>
                                            {city.name.charAt(0).toUpperCase()}
                                        </Typography>
                                    </div>
                                ) : null}

                                <ListItem button onClick={() => handleCityClick(city.name)}
                                          selected={selectedCity === city}>
                                    <ListItemText primary={city.name}/>
                                </ListItem>
                            </div>
                        ))}
                    </List>
                </div>
            </div>


        </div>
    );
}

export default CityList